﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace _80X_CG_Frame.Utils
{
    public static class TcpAsyncConnect
    {
        /// <summary>
        /// TcpClient异步连接
        /// </summary>
        /// <param name="client">传入连接</param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="times">重试次数,默认5次即一共进行1+5次连接</param>
        /// <returns>异步连接结果</returns>
        public async static Task<bool> ConnectAsync(TcpClient client, string ip, int port, int times = 5)
        {
            //异步连接任务列表
            List<Task> tasks = new List<Task>();
            int fail_count = 0;
            //Task t = null;
            if (!client.Connected)
            {
                try
                {
                    tasks.Add(client.ConnectAsync(ip, port));
                }
                catch (Exception e)
                {
                    //System.Console.WriteLine(e.ToString());
                    System.Console.WriteLine("地址无效");
                }
            }
            for (int i = 0; i < times; i++)
            {
                
                if(!client.Connected)
                {
                    tasks.Add(tasks.Last().ContinueWith(f =>
                    {
                        if (client.Client != null&&!client.Connected)
                        {
                            fail_count++;
                            //System.Console.WriteLine("第" + fail_count + "次连接失败,尝试重新连接");
                            try
                            {
                                tasks.Add(client.ConnectAsync(ip, port));
                            }
                            catch (Exception e)
                            {
                                //System.Console.WriteLine(e.ToString());
                                System.Console.WriteLine("地址无效");
                            }
                        }
                    }));
                    //TaskContinuationOptions.NotOnRanToCompletion);
                }
            }
            return await Task.WhenAll(tasks.ToArray()).ContinueWith(f =>
            {
                if (client == null || client.Client == null || !client.Connected)
                {
                    //System.Console.WriteLine("连接失败");
                    return false;
                }
                if (client.Connected)
                {
                    System.Console.WriteLine("连接成功");
                    return true;
                }
                //System.Console.WriteLine("连接失败");
                return false;

            }
            );
        }
    }
}
